package com.springboot.bookmanegersystem.service.imp;

import com.springboot.bookmanegersystem.mapper.UserMapper;
import com.springboot.bookmanegersystem.model.UserInfo;
import com.springboot.bookmanegersystem.model.req.UserRequestParam;
import com.springboot.bookmanegersystem.model.resp.Result;
import com.springboot.bookmanegersystem.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-05-08
 * Time: 20:08
 */
@Slf4j
@Service
public class UserServiceImp implements UserService {

    private static final String SALT = "yang-yao-wei";
    private static final String USERINFO = "USERINFO";

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result userRegister(UserRequestParam userRequestParam) {
        // 1、检验参数是否合法
        if (userRequestParam == null
                || !StringUtils.hasText(userRequestParam.getUsername())
                || !StringUtils.hasText(userRequestParam.getPassword())) {
            log.info("[userRegister]: 参数不合法!");
            return Result.error("参数不合法");
        }
        // 2、检验用户名是否包含特殊字符
        // 用户名只能包含 数字、字母、下划线
        String rule = "[^a-zA-Z0-9_]";
        String username = userRequestParam.getUsername();
        boolean isContainsSpecialCharacters =
                username.matches(".*" + rule + ".*");
        if (isContainsSpecialCharacters) {
            log.info("[userRegister]: 用户名包含特殊字符!");
            return Result.error("用户名包含特殊字符");
        }
        // 3、查询用户名是否存在
        UserInfo userInfo = userMapper.queryUserInfoByUsername(username);
        if (userInfo != null) {
            log.info("[userRegister]: "+username+" 已经存在, 不可重复注册!");
            return Result.error(username+" 已经存在, 不可重复注册!");
        }
        // 4、加密密码
        String password = userRequestParam.getPassword();
        // 1)加盐
        String newPasswordSalt = SALT + password + SALT;
        // 2)加密
        String newPasswordEncrypt = DigestUtils.md5DigestAsHex(newPasswordSalt.getBytes(StandardCharsets.UTF_8));
        // 5、将用户名、密码存储到数据库中
        Integer result = userMapper.insert(username, newPasswordEncrypt);
        return result == 1 ? Result.success(username+" 注册成功") : Result.fatal();
    }

    @Override
    public Result userLogin(UserRequestParam userRequestParam, HttpSession session) {
        // 1、校验参数是否合法
        if (userRequestParam == null
                || !StringUtils.hasText(userRequestParam.getUsername())
                || !StringUtils.hasText(userRequestParam.getPassword())) {
            log.info("[userLogin]: 参数不合法!");
            return Result.error("参数不合法");
        }
        // 2、校验账号是否包含特殊字符
        String rule = "[^a-zA-Z0-9_]";
        String username = userRequestParam.getUsername();
        boolean isContainsSpecialCharacters =
                username.matches(".*" + rule + ".*");
        if (isContainsSpecialCharacters) {
            log.info("[userRegister]: 用户名包含特殊字符!");
            return Result.error("用户名包含特殊字符");
        }
        // 3、判断用户名是否存在
        //   1) 如果不存在，直接返回
        //   2) 如果存在，将密码加密，与查询数据库到的密码进行对比
        // 根据用户名查询user表
        UserInfo userInfo = userMapper.queryUserInfoByUsername(username);
        if (userInfo == null) {
            log.info("[userLogin]: " + username + " 不存在!");
            return Result.error(username+" 不存在");
        }
        // 对密码进行加密，然后进行对比
        String password = userRequestParam.getPassword();
        // 1)加盐
        String newPasswordSalt = SALT + password + SALT;
        // 2)加密
        String newPasswordEncrypt = DigestUtils.md5DigestAsHex(newPasswordSalt.getBytes(StandardCharsets.UTF_8));
        if (newPasswordEncrypt.equals(userInfo.getPassword())) {
            log.info("[userLogin]: "+username+" 登录成功!");
            // session保存脱敏后的用户信息
            userInfo.setPassword("");
            session.setAttribute("USERINFO", userInfo);
            return Result.success(username+" 登录成功");
        }
        log.info("[userLogin]: "+username+" 密码错误, 登录失败!");
        return Result.error("密码错误");
    }
}
